// ============================================
// 16 - 迭代器和闭包 (Iterators and Closures)
// ============================================

/// 迭代器和闭包是 Rust 的函数式编程特性

// ==================== 闭包基础 ====================

/// 闭包定义和使用
pub fn closure_basics() {
    println!("\n=== 闭包基础 ===");
    
    // 基本闭包
    let add_one = |x| x + 1;
    println!("5 + 1 = {}", add_one(5));
    
    // 带类型注解的闭包
    let add = |x: i32, y: i32| -> i32 { x + y };
    println!("10 + 20 = {}", add(10, 20));
    
    // 多行闭包
    let multiply = |x, y| {
        println!("计算 {} * {}", x, y);
        x * y
    };
    println!("结果: {}", multiply(3, 4));
}

/// 闭包类型推断
pub fn closure_type_inference() {
    println!("\n=== 闭包类型推断 ===");
    
    let example_closure = |x| x;
    
    let s = example_closure(String::from("hello"));
    println!("字符串: {}", s);
    
    // 一旦类型被推断，就不能改变
    // let n = example_closure(5); // ❌ 错误: 类型不匹配
}

/// 捕获环境
pub fn capturing_environment() {
    println!("\n=== 捕获环境 ===");
    
    let x = 4;
    
    // 不可变借用
    let equal_to_x = |z| z == x;
    println!("5 == 4? {}", equal_to_x(5));
    
    // 可变借用
    let mut list = vec![1, 2, 3];
    println!("修改前: {:?}", list);
    
    let mut borrows_mutably = || list.push(7);
    borrows_mutably();
    println!("修改后: {:?}", list);
    
    // 获取所有权
    let consumes = move || {
        println!("移动后: {:?}", list);
        list
    };
    let _result = consumes();
    // println!("{:?}", list); // ❌ 错误: list 已被移动
}

// ==================== Fn Trait ====================

/// Fn, FnMut, FnOnce trait
pub fn fn_traits() {
    println!("\n=== Fn Traits ===");
    
    println!("闭包实现以下 trait 之一:");
    println!("1. FnOnce - 获取所有权，只能调用一次");
    println!("2. FnMut - 可变借用，可多次调用");
    println!("3. Fn - 不可变借用，可多次调用");
}

fn apply<F>(f: F)
where
    F: FnOnce(),
{
    f();
}

fn apply_twice<F>(mut f: F)
where
    F: FnMut(),
{
    f();
    f();
}

pub fn using_fn_traits() {
    println!("\n=== 使用 Fn Traits ===");
    
    let s = String::from("hello");
    
    apply(move || {
        println!("FnOnce: {}", s);
    });
    
    let mut count = 0;
    apply_twice(|| {
        count += 1;
        println!("FnMut 调用 {} 次", count);
    });
}

// ==================== 迭代器基础 ====================

/// 迭代器简介
pub fn iterator_basics() {
    println!("\n=== 迭代器基础 ===");
    
    let v = vec![1, 2, 3, 4, 5];
    
    // 创建迭代器
    let v_iter = v.iter();
    
    // 使用 for 循环
    for val in v_iter {
        println!("值: {}", val);
    }
}

/// Iterator trait
pub fn iterator_trait() {
    println!("\n=== Iterator Trait ===");
    
    let v = vec![1, 2, 3];
    let mut v_iter = v.iter();
    
    // next 方法
    assert_eq!(v_iter.next(), Some(&1));
    assert_eq!(v_iter.next(), Some(&2));
    assert_eq!(v_iter.next(), Some(&3));
    assert_eq!(v_iter.next(), None);
    
    println!("迭代器遍历完成");
}

/// iter, iter_mut, into_iter
pub fn iterator_types() {
    println!("\n=== 迭代器类型 ===");
    
    let v = vec![1, 2, 3];
    
    // iter() - 不可变引用
    for val in v.iter() {
        println!("不可变引用: {}", val);
    }
    
    // iter_mut() - 可变引用
    let mut v = vec![1, 2, 3];
    for val in v.iter_mut() {
        *val += 10;
    }
    println!("修改后: {:?}", v);
    
    // into_iter() - 获取所有权
    let v = vec![1, 2, 3];
    for val in v.into_iter() {
        println!("拥有所有权: {}", val);
    }
    // println!("{:?}", v); // ❌ 错误: v 已被移动
}

// ==================== 消费适配器 ====================

/// 消费适配器
pub fn consuming_adaptors() {
    println!("\n=== 消费适配器 ===");
    
    let v = vec![1, 2, 3, 4, 5];
    
    // sum - 求和
    let total: i32 = v.iter().sum();
    println!("总和: {}", total);
    
    // collect - 收集为集合
    let v2: Vec<i32> = v.iter().cloned().collect();
    println!("收集: {:?}", v2);
    
    // count - 计数
    let count = v.iter().count();
    println!("数量: {}", count);
    
    // max, min
    let max = v.iter().max();
    let min = v.iter().min();
    println!("最大值: {:?}, 最小值: {:?}", max, min);
}

// ==================== 迭代器适配器 ====================

/// 迭代器适配器
pub fn iterator_adaptors() {
    println!("\n=== 迭代器适配器 ===");
    
    let v = vec![1, 2, 3, 4, 5];
    
    // map - 映射
    let v2: Vec<i32> = v.iter().map(|x| x * 2).collect();
    println!("映射翻倍: {:?}", v2);
    
    // filter - 过滤
    let v3: Vec<&i32> = v.iter().filter(|x| **x % 2 == 0).collect();
    println!("过滤偶数: {:?}", v3);
    
    // chain - 链接
    let v4 = vec![6, 7, 8];
    let v5: Vec<i32> = v.iter().chain(v4.iter()).cloned().collect();
    println!("链接: {:?}", v5);
    
    // zip - 组合
    let names = vec!["Alice", "Bob", "Charlie"];
    let scores = vec![90, 85, 95];
    let pairs: Vec<_> = names.iter().zip(scores.iter()).collect();
    println!("组合: {:?}", pairs);
}

/// 更多迭代器适配器
pub fn more_iterator_adaptors() {
    println!("\n=== 更多迭代器适配器 ===");
    
    let v = vec![1, 2, 3, 4, 5];
    
    // enumerate - 枚举索引
    for (i, val) in v.iter().enumerate() {
        println!("索引 {}: {}", i, val);
    }
    
    // skip - 跳过
    let skip_two: Vec<&i32> = v.iter().skip(2).collect();
    println!("跳过前2个: {:?}", skip_two);
    
    // take - 获取
    let take_three: Vec<&i32> = v.iter().take(3).collect();
    println!("获取前3个: {:?}", take_three);
    
    // rev - 反转
    let reversed: Vec<&i32> = v.iter().rev().collect();
    println!("反转: {:?}", reversed);
}

// ==================== 自定义迭代器 ====================

/// 自定义迭代器
struct Counter {
    count: u32,
}

impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }
}

impl Iterator for Counter {
    type Item = u32;
    
    fn next(&mut self) -> Option<Self::Item> {
        if self.count < 5 {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}

pub fn custom_iterator() {
    println!("\n=== 自定义迭代器 ===");
    
    let counter = Counter::new();
    
    for num in counter {
        println!("计数: {}", num);
    }
    
    // 使用自定义迭代器的适配器
    let sum: u32 = Counter::new()
        .zip(Counter::new().skip(1))
        .map(|(a, b)| a * b)
        .filter(|x| x % 3 == 0)
        .sum();
    
    println!("计算结果: {}", sum);
}

// ==================== fold 和 reduce ====================

/// fold 和 reduce
pub fn fold_and_reduce() {
    println!("\n=== fold 和 reduce ===");
    
    let numbers = vec![1, 2, 3, 4, 5];
    
    // fold - 折叠/累积
    let sum = numbers.iter().fold(0, |acc, x| acc + x);
    println!("fold 求和: {}", sum);
    
    let product = numbers.iter().fold(1, |acc, x| acc * x);
    println!("fold 求积: {}", product);
    
    // reduce - 类似 fold，但没有初始值
    let sum2 = numbers.iter().copied().reduce(|acc, x| acc + x);
    println!("reduce 求和: {:?}", sum2);
}

// ==================== 无限迭代器 ====================

/// 无限迭代器
pub fn infinite_iterators() {
    println!("\n=== 无限迭代器 ===");
    
    // (0..) 创建无限序列
    let first_10_squares: Vec<i32> = (0..)
        .map(|x| x * x)
        .take(10)
        .collect();
    
    println!("前10个平方数: {:?}", first_10_squares);
    
    // cycle - 循环
    let v = vec![1, 2, 3];
    let cycled: Vec<&i32> = v.iter().cycle().take(7).collect();
    println!("循环: {:?}", cycled);
    
    // repeat
    use std::iter;
    let repeated: Vec<i32> = iter::repeat(5).take(3).collect();
    println!("重复: {:?}", repeated);
}

// ==================== 实际应用示例 ====================

#[derive(Debug)]
struct Shoe {
    size: u32,
    style: String,
}

fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
    shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}

pub fn practical_example() {
    println!("\n=== 实际应用: 筛选鞋子 ===");
    
    let shoes = vec![
        Shoe {
            size: 10,
            style: String::from("运动鞋"),
        },
        Shoe {
            size: 13,
            style: String::from("凉鞋"),
        },
        Shoe {
            size: 10,
            style: String::from("靴子"),
        },
    ];
    
    let my_shoes = shoes_in_size(shoes, 10);
    println!("我的鞋码 (10): {:?}", my_shoes);
}

/// 数据处理管道
pub fn data_pipeline() {
    println!("\n=== 数据处理管道 ===");
    
    let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    let result: Vec<i32> = data
        .iter()
        .filter(|&&x| x % 2 == 0)  // 过滤偶数
        .map(|&x| x * x)           // 平方
        .filter(|&x| x > 10)       // 大于10
        .collect();
    
    println!("处理结果: {:?}", result);
}

// ==================== 性能比较 ====================

/// 迭代器 vs 循环
pub fn performance_comparison() {
    println!("\n=== 性能比较 ===");
    
    println!("迭代器的优势:");
    println!("1. 零成本抽象 - 编译后性能与手写循环相同");
    println!("2. 更简洁的代码");
    println!("3. 更少的错误");
    println!("4. 易于组合和链式调用");
}

// ==================== 最佳实践 ====================

/// 迭代器和闭包最佳实践
pub fn best_practices() {
    println!("\n=== 最佳实践 ===");
    
    println!("迭代器:");
    println!("1. 优先使用迭代器而不是索引循环");
    println!("2. 使用链式调用组合操作");
    println!("3. 理解 iter/iter_mut/into_iter 的区别");
    println!("4. 利用惰性求值提高性能");
    
    println!("\n闭包:");
    println!("1. 适当使用类型注解提高可读性");
    println!("2. 理解捕获模式（move vs 借用）");
    println!("3. 注意 Fn trait 的区别");
    println!("4. 避免过度使用闭包影响可读性");
}

/// 主函数 - 演示所有功能
#[allow(dead_code)]
pub fn main() {
    println!("╔════════════════════════════════════════╗");
    println!("║   Rust 迭代器和闭包教程                ║");
    println!("╚════════════════════════════════════════╝");
    
    closure_basics();
    closure_type_inference();
    capturing_environment();
    fn_traits();
    using_fn_traits();
    
    iterator_basics();
    iterator_trait();
    iterator_types();
    consuming_adaptors();
    iterator_adaptors();
    more_iterator_adaptors();
    custom_iterator();
    fold_and_reduce();
    infinite_iterators();
    
    practical_example();
    data_pipeline();
    performance_comparison();
    best_practices();
    
    println!("\n✅ 迭代器和闭包教程完成！");
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_closure() {
        let add_one = |x| x + 1;
        assert_eq!(add_one(5), 6);
    }
    
    #[test]
    fn test_iterator_sum() {
        let v = vec![1, 2, 3, 4, 5];
        let sum: i32 = v.iter().sum();
        assert_eq!(sum, 15);
    }
    
    #[test]
    fn test_map_collect() {
        let v = vec![1, 2, 3];
        let v2: Vec<i32> = v.iter().map(|x| x * 2).collect();
        assert_eq!(v2, vec![2, 4, 6]);
    }
    
    #[test]
    fn test_filter() {
        let v = vec![1, 2, 3, 4, 5, 6];
        let evens: Vec<&i32> = v.iter().filter(|&&x| x % 2 == 0).collect();
        assert_eq!(evens, vec![&2, &4, &6]);
    }
    
    #[test]
    fn test_custom_iterator() {
        let counter = Counter::new();
        let sum: u32 = counter.sum();
        assert_eq!(sum, 15);
    }
    
    #[test]
    fn test_shoes_in_size() {
        let shoes = vec![
            Shoe {
                size: 10,
                style: String::from("sneaker"),
            },
            Shoe {
                size: 13,
                style: String::from("sandal"),
            },
            Shoe {
                size: 10,
                style: String::from("boot"),
            },
        ];
        
        let in_my_size = shoes_in_size(shoes, 10);
        assert_eq!(in_my_size.len(), 2);
    }
}

